//
//  ExpenseAddDetailsViewController.swift
//  NewCard
//
//  Created by yihui on 2017/11/19.
//  Copyright © 2017年 yihui. All rights reserved.
//

import UIKit

class ExpenseAddDetailsViewController: UIViewController {

    // 属性
    @IBOutlet weak var contectView: UIView!
    
    // 银行名称
    @IBOutlet weak var bankNameField: UITextField!
    // 银行卡号
    @IBOutlet weak var bankCardField: UITextField!
    // 使用类型
    @IBOutlet weak var useTypeField: UITextField!
    // 金额
    @IBOutlet weak var moneyField: UITextField!
    // 备注
    @IBOutlet weak var noteField: UITextField!
    // 按钮
    @IBOutlet weak var expenseButton: UIButton!
    // 存储 UITextField 的 frame
    fileprivate var textFieldFrame : CGRect!
    // 模型
    var model : ExpenseModel!
    var cardModel : CardModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()

    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        //HHLog("销毁")
    }

}

// // MARK: - ui设置
extension ExpenseAddDetailsViewController {
    
    fileprivate func setupUI() {
        
        setupTextFieldDalegate()
        
        setupNotification()
        
        bankNameField.text = model.bankName
        bankCardField.text = String(model.bankCard)
        useTypeField.text = model.useType
        
        if model.useType == "消费" {
            expenseButton.setTitle("确认消费", for: .normal)
        } else if model.useType == "还款" {
            expenseButton.setTitle("确认还款", for: .normal)
        }
        
    }

}



//MARK: -- 键盘和UITextField代理
extension ExpenseAddDetailsViewController : UITextFieldDelegate {
    
    // 通知
    fileprivate func setupNotification() {
        // 键盘监听通知
        NotificationCenter.default.addObserver(self, selector: #selector(self.kbFrameChanged(_:)), name: .UIKeyboardWillChangeFrame, object: nil)
    }
    
    fileprivate func setupTextFieldDalegate() {
        
        moneyField.delegate = self
        noteField.delegate = self
        
    }
    //MARK: -- 获取当前被选择的UITextField
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textFieldFrame = textField.frame
    }
    
    //MARK: -- Return 关闭键盘
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        textField.resignFirstResponder()
        
        return true
    }
    //MARK: -- 弹出键盘上移UI
    @objc fileprivate func kbFrameChanged( _ notification : Notification) {
        
        let info = notification.userInfo
        let kbRect = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let bottomSpacing: CGFloat = 50
        let maxY = view.frame.height - (textFieldFrame.maxY + bottomSpacing)
        let offset : CGFloat = maxY - kbRect.height
        let offsetY : CGFloat = (kbRect.origin.y < view.frame.height) ? offset : 0
        if (kbRect.height) > (view.bounds.height-textFieldFrame.maxY-bottomSpacing) {
            UIView.animate(withDuration: 0.3) {
                self.contectView.transform = CGAffineTransform(translationX: 0, y: offsetY)
            }
        }
    }
    //MARK: -- 关闭空白处关闭键盘
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}


// MARK: - 点击事件
extension ExpenseAddDetailsViewController {
    
    @IBAction func expenseBtnClick(_ sender: Any) {
        
        guard expenseSetup() else {
            return
        }
        
        self.navigationController?.popViewController(animated: true)
    }
    
}


// MARK: -  处理数据
extension ExpenseAddDetailsViewController {
    
    fileprivate func expenseSetup() -> Bool {
        
        guard let name = bankNameField.text,
                  bankNameField.text != "",
              let card = bankCardField.text,
                  bankCardField.text != "",
              let money = moneyField.text,
                  moneyField.text != "" else {
            return false
        }
        
        var note : String!
        if noteField.text == nil || noteField.text == ""  {
            note = "无备注"
        }
        
        
        let data = ExpenseModel()
        data.id = model.id
        data.bankName = name
        data.bankCard = Int(card)!
        data.useType = model.useType
        data.money = Double(money)!
        data.note = note
        
        if OpenData.insertData(data: data) {
            
            if data.useType == "消费" {
                cardModel.usableAmount = (cardModel.usableAmount - data.money)
            } else if data.useType == "还款" {
                cardModel.usableAmount = (cardModel.usableAmount + data.money)
            }
            
            return OpenData.updateData(data: cardModel)
        }
        
        return false
    }
    
    //MARK: -- 格式化时间
    private func formData(_ tempData: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "YYYY-MM-dd"
        return formatter.string(from: tempData)
    }
}


